/**
 * create by zhangpu
 * date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.fuyou.marshall;

import com.acooly.core.utils.Strings;
import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.message.MessageFactory;
import com.acooly.module.openapi.client.provider.fuyou.domain.FuyouResponse;
import com.acooly.module.openapi.client.provider.fuyou.enums.FuyouServiceEnum;
import com.acooly.module.openapi.client.provider.fuyou.enums.FuyouServiceTypeEnum;
import com.acooly.module.openapi.client.provider.fuyou.utils.DESCoderFuyou;
import com.acooly.module.openapi.client.provider.fuyou.utils.XmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zhangpu
 */
@Service
@Slf4j
public class FuyouResponseUnmarshall extends FuyouMarshallSupport implements ApiUnmarshal<FuyouResponse, String> {

    @Resource(name = "fuyouMessageFactory")
    private MessageFactory messageFactory;


    @SuppressWarnings("unchecked")
    @Override
    public FuyouResponse unmarshal(String message, String serviceName) {
        try {
            String decodeDataContent = message;
            if(FuyouServiceTypeEnum.APIFMS.equals(FuyouServiceEnum.find(serviceName).getType())) {
                //解密报文
                decodeDataContent = DESCoderFuyou.desDecrypt(message, DESCoderFuyou.getKeyLength8(getSignKey(serviceName)));
            }
            log.info("响应报文:{}", decodeDataContent);
            FuyouResponse response = doUnmarshall(decodeDataContent, serviceName);
            if(FuyouServiceTypeEnum.APIFMS.equals(FuyouServiceEnum.find(serviceName).getType())||FuyouServiceTypeEnum.FM.equals(FuyouServiceEnum.find(serviceName).getType())) {
                if (FuyouServiceEnum.find(serviceName) != FuyouServiceEnum.FUYOU_ORDER_PAY) {
                    if (Strings.isNotBlank(response.getSign())) {
                        // 验签
                        doVerify(response.getSignStr(), response.getSign(), serviceName);
                    }
                }else if(Strings.equals(response.getResponseCode(),"0000")){//针对富友协议支付特殊处理
                    // 验签
                    doVerify(response.getSignStr(), response.getSign(), serviceName);
                }
            }
            return response;
        } catch (Exception e) {
            throw new ApiClientException("解析响应报文错误:" + e.getMessage());
        }
    }

    protected FuyouResponse doUnmarshall(String responseMessage, String serviceName) {
        FuyouResponse response = (FuyouResponse) messageFactory.getResponse(FuyouServiceEnum.find(serviceName).getKey());
        response = XmlUtils.toBean(responseMessage, response.getClass());
        return response;
    }

    public void setMessageFactory(MessageFactory messageFactory) {
        this.messageFactory = messageFactory;
    }

}
